﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using OpticalPowerMeter.UserControls;
using System.ComponentModel;
using OpticalPowerMeter.Converts;


namespace OpticalPowerMeter
{
    /// <summary>
    /// 光功率计测试主界面
    /// </summary>
    public partial class MainWindow : Window
    {

        public MainWindow()
        {
            InitializeComponent();
            InitMetersGrid();  //初始化机型界面
            InitSnsGrid(); //初始化SN输入界面
            InitTestStepBox(); //初始化测试项
            InitMainWindowSize();//初始化窗口尺寸
            InitProductNameBox(); //初始化机型名称列表
            ProductManagement.GetInstance().ProductNameListChanged += new EventHandler<ProductListChangedArgs>(ProductListChanged); //型号名称清单发生变更时，刷新清单
        }


        //初始化机型列表
        private void InitProductNameBox()
        {
            ProductManagement productManagement = ProductManagement.GetInstance();
            List<string> productNameList = productManagement.GetProductList();
            ProductNameBox.ItemsSource = productNameList;
            string selectName = CurrentConfigManagement.GetIntance().GetSelectProductName();
            if (selectName == "")
            {
                ProductNameBox.SelectedIndex = 0;
            }
            else
            {
                ProductNameBox.SelectedValue = selectName;
            }
        }


        //设置机型按钮点击时，显示弹出ProductEditWindow
        private void ProductSetMenu_Click(object sender,RoutedEventArgs args) {
            ProductEditWindow productEdit = new ProductEditWindow();
            productEdit.Height = Height * 0.8;
            productEdit.Width = Width * 0.8;
            productEdit.Owner = this;
            productEdit.ShowDialog();
        }


        //设置串口组按钮点击时，弹出SerialGroupWindow
        private void SerialGroupSetMenu_Click(object sender,RoutedEventArgs args) {
            SerialGroupWindow serialGroup = new SerialGroupWindow();
            serialGroup.Height = Height * 0.8;
            serialGroup.Width = Width * 0.8;
            serialGroup.Owner = this;
            serialGroup.ShowDialog();
        }


        //设置线性组按钮点击时，弹出LinearGroupWindow
        private void LinearGroupSetMenu_Click(object sender,RoutedEventArgs args) {
            LinearGroupWindow linearGroup = new LinearGroupWindow();
            linearGroup.Height = Height * 0.8;
            linearGroup.Width = Width * 0.8;
            linearGroup.Owner = this;
            linearGroup.ShowDialog();
        }

        //设置复查组按钮点击时，弹出CheckGroupWindow
        private void CheckGroupSetMenu_Click(object sender,RoutedEventArgs args) {
            CheckGroupWindow checkGroup = new CheckGroupWindow();
            checkGroup.Height = Height * 0.8;
            checkGroup.Width = Width * 0.8;
            checkGroup.Owner = this;
            checkGroup.ShowDialog();
        }

        //光开关设置菜单点击时，弹出OpticalSwitchWindow
        private void OpticalSwitchSetMenu_Click(object sender,RoutedEventArgs args) {
            OpticalSwitchWindow opticalSwitchWindow = new OpticalSwitchWindow();
            opticalSwitchWindow.Height = Height * 0.8;
            opticalSwitchWindow.Width = Width * 0.8;
            opticalSwitchWindow.Owner = this;
            opticalSwitchWindow.ShowDialog();
        }

        //初始化主界面尺寸
        private void InitMainWindowSize()
        {
            Size size = CurrentConfigManagement.GetIntance().GetMainWindowSize();
            double width = size.Width;
            double height = size.Height;
            if(width!=-1 && height != -1)
            {
                this.Width = width;
                this.Height = height;
            }
        }

        //初始化测试步骤
        private void InitTestStepBox()
        {
            List<TestSteps> testSteps = CurrentConfigManagement.GetIntance().GetStepList();
            foreach (TestSteps step in testSteps)
            {
                switch (step)
                {
                    case TestSteps.Linear:
                        SetValue(LinearIsSelectedProperty,true);
                        break;
                    case TestSteps.Correct:
                        SetValue(CorrectionIsSelectedProperty,true);
                        break;
                    case TestSteps.CheckValue:
                        SetValue(CheckIsSelectedProperty,true);
                        break;
                }
            }
        }

        //初始化Sn输入grid
        private void InitSnsGrid()
        {
            for(int i = 0; i < 7; i++)
            {
                SnEnterControl snEnterControl = new SnEnterControl();
                SnGrid.Children.Add(snEnterControl);
                Grid.SetRow(snEnterControl,i);
            }
        }

        //初始化设备清单界面
        private void InitMetersGrid()
        {
            for (int i = 0; i < 8; i++)
            {
                OpticalPowerMeterControl opticalPowerMeter = new OpticalPowerMeterControl();
                opticalPowerMeter.ConnectState = ConnectState.Disconnect;
                opticalPowerMeter.MeterStatus = "准备中";
                App.Current.Dispatcher.Invoke(new Action(() =>
                {
                    opticalPowerMeter.MeterStatusBrush = new SolidColorBrush(Color.FromRgb(20, 14, 160));
                }));
                MetersGrid.Children.Add(opticalPowerMeter);
                Grid.SetRow(opticalPowerMeter, i / 4);
                Grid.SetColumn(opticalPowerMeter, i % 4);
                opticalPowerMeter.HorizontalAlignment = HorizontalAlignment.Left;
                opticalPowerMeter.VerticalAlignment = VerticalAlignment.Center;
                opticalPowerMeter.MeterName = (MeterName)i;
                opticalPowerMeter.Margin = new Thickness(5, 5, 0, 0);
            }
        }
        

        #region 界面绑定的显示属性
        //ComBox、TextBox边距
        static DependencyProperty BoxMarginProperty = DependencyProperty.Register(
            "BoxMargin",
            typeof(Thickness),
            typeof(MainWindow)
            );

        //ComBox、TextBox宽度
        static DependencyProperty BoxWidthProperty = DependencyProperty.Register(
            "BoxWidth",
            typeof(double),
            typeof(MainWindow)
            );

        //ComboBox、TextBox高度
        static DependencyProperty BoxHeightProperty = DependencyProperty.Register(
            "BoxHeight",
            typeof(double),
            typeof(MainWindow)
            );


        //机型选择的边距，目前这部分未做设置
        static DependencyProperty LabelMarginProperty = DependencyProperty.Register(
            "LabelMargin",
            typeof(Thickness),
            typeof(MainWindow)
            );

        //机型选择字体大小
        static DependencyProperty LabelFontSizeProperty = DependencyProperty.Register(
            "LabelFontSize",
            typeof(double),
            typeof(MainWindow)
            );

        //按钮的高度
        static DependencyProperty ButtonHeightProperty = DependencyProperty.Register(
            "ButtonHeight",
            typeof(double),
            typeof(MainWindow)
            );

        //按钮宽度
        static DependencyProperty ButtonWidthProperty = DependencyProperty.Register(
            "ButtonWidth",
            typeof(double),
            typeof(MainWindow)
            );

        //按钮的字体大小
        static DependencyProperty ButtonFontSizeProperty = DependencyProperty.Register(
            "ButtonFontSize",
            typeof(double),
            typeof(MainWindow)
            );

        //线性是否选中
        static DependencyProperty LinearIsSelectedProperty = DependencyProperty.Register(
            "LinearIsSelected",
            typeof(bool),
            typeof(MainWindow)
            );

        //整偏是否选中
        static DependencyProperty CorrectionIsSelectedProperty = DependencyProperty.Register(
            "CorrectionIsSelected",
            typeof(bool),
            typeof(MainWindow)
            );

        //检查是否选中
        static DependencyProperty CheckIsSelectedProperty = DependencyProperty.Register(
            "CheckIsSelected",
            typeof(bool),
            typeof(MainWindow)
            );

        //整偏按钮边距
        static DependencyProperty CorrectionButtonMarginProperty = DependencyProperty.Register("CorrectionButtonMargin",typeof(Thickness),typeof(MainWindow));

        //检查按钮边距
        static DependencyProperty CheckButtonMarginProperty = DependencyProperty.Register("CheckButtonMargin",typeof(Thickness),typeof(MainWindow));
        #endregion


        //显示区域内容变更时，让滑块始终在最低端
        private void MoveScrollToEnd(object sender, TextChangedEventArgs args)
        {
            LogTextBox.ScrollToEnd();
        }


        //选择的机型发生变化时，保存最新内容至本地
        private void ProductNameSelectionChanged(object sender, SelectionChangedEventArgs args)
        {
            object selection = ProductNameBox.SelectedValue;
            if (selection == null)
            {
                return;
            }
            string productName = ProductNameBox.SelectedValue.ToString().Trim();
            CurrentConfigManagement currrentConfig = CurrentConfigManagement.GetIntance();
            currrentConfig.SaveSeletProductName(productName);
        }


        //窗口大小变化时，刷新控件的位置，尺寸等
        private void FrameSize_Changed(object sender, SizeChangedEventArgs args)
        {
            Grid grid = sender as Grid;
            double parentHeight = grid.ActualHeight; //获取父元素的高与宽
            double parentWidth = grid.ActualWidth;
            string name = grid.Name;
            switch (name)
            {
                #region 刷新机型选择框部分
                case "SelectTypeFrame":  
                    //"机型设置"，字样根据外部Grid的宽度的30%设置字号
                    double fontSize = Math.Round((parentWidth*0.3 - 10) / 4, 1);
                    SetValue(LabelFontSizeProperty, fontSize);
                    ////设置底部ComboBox高度取label高度
                    double boxHeight = fontSize * 1.27;
                    SetValue(BoxHeightProperty, boxHeight);
                    //底部底部ComBox宽度取父Grid宽度70%-20
                    double boxWidth = Math.Round(parentWidth * 0.7 - 20, 1);
                    SetValue(BoxWidthProperty, boxWidth);
                    ////设置底部标签边距
                    //double labelLeft = Math.Round((parentWidth - fontSize * 4.7 - boxWidth) / 2, 1);
                    //SetValue(LabelMarginProperty, new Thickness(labelLeft, 0, 0, 0));
                    ////设置底部ComboBox左边距，在父Grid的30%往又10个像素点
                    double boxLeft = Math.Round(parentWidth*0.3 + 10, 1);
                    SetValue(BoxMarginProperty, new Thickness(boxLeft, 0, 0, 0));
                    break;
                #endregion
                #region 刷新机型选择框部分
                case "MetersGrid":
                    foreach (UIElement uIElement in grid.Children)
                    {
                        OpticalPowerMeterControl meter = uIElement as OpticalPowerMeterControl;
                        meter.Height = Math.Round((parentHeight - 30) / 2, 2);
                        meter.Width = Math.Round((parentWidth - 50) / 4, 2);
                    }
                    break;
                #endregion
                #region 刷新Sn输入框
                case "SnGrid":
                    foreach (UIElement uIElement in grid.Children) {
                        SnEnterControl snControl = uIElement as SnEnterControl;
                        snControl.Height = Math.Round(parentHeight / 7, 2);
                        snControl.Width = parentWidth;
                    }
                    break;
                #endregion
                #region 刷新测试项界面
                case "TestStepGrid":
                    double buttonWidth = Math.Round((parentWidth - 30) / 3,2); //按钮宽度
                    double buttonHeight = Math.Round(buttonWidth / 2.5, 2); //按钮高度与宽度比例为10:25
                    SetValue(ButtonWidthProperty, buttonWidth);
                    SetValue(ButtonHeightProperty, buttonHeight);
                    double buttonFontSize = Math.Round((buttonHeight - 10)/1.27,1); //字号
                    SetValue(ButtonFontSizeProperty,buttonFontSize);
                    double correctionLeft = buttonWidth + 15; //整偏按钮左边距
                    SetValue(CorrectionButtonMarginProperty,new Thickness(correctionLeft,0,0,0));
                    double checkLeft = buttonWidth * 2 + 25; //检查按钮左边距
                    SetValue(CheckButtonMarginProperty,new Thickness(checkLeft,0,0,0));
                    break;
                #endregion
            }
        }


        //测试项按钮点击时,刷新选中状态
        private void TestStepButton_Click(object sender, RoutedEventArgs args) {
            CurrentConfigManagement currentConfig = CurrentConfigManagement.GetIntance();
            Button button = sender as Button;
            string buttonName = button.Name;
            switch (buttonName)
            {
                case "LinearButton":
                    bool linearIsSelected = (bool)GetValue(LinearIsSelectedProperty);
                    SetValue(LinearIsSelectedProperty, !linearIsSelected); //点击时，切换选中/非选中
                    #region 在配置文件中保留最后一次的选项
                    if (linearIsSelected)
                    {
                        currentConfig.RemoveStep(TestSteps.Linear);
                    }
                    else
                    {
                        currentConfig.AddStep(TestSteps.Linear);
                    }
                    #endregion
                    break;
                case "CorrectionButton":
                    bool correctionIsSelected = (bool)GetValue(CorrectionIsSelectedProperty);
                    SetValue(CorrectionIsSelectedProperty,!correctionIsSelected);
                    if (correctionIsSelected) {
                        currentConfig.RemoveStep(TestSteps.Correct);
                    }
                    else
                    {
                        currentConfig.AddStep(TestSteps.Correct);
                    }
                    break;
                case "CheckButton":
                    bool checkIsSelected = (bool)GetValue(CheckIsSelectedProperty);
                    SetValue(CheckIsSelectedProperty,!checkIsSelected);
                    if (checkIsSelected) {
                        currentConfig.RemoveStep(TestSteps.CheckValue);
                    }
                    else
                    {
                        currentConfig.AddStep(TestSteps.CheckValue);
                    }
                    break;
            }
        }


        //关闭窗口时，保存当前窗口的尺寸
        private void MainWindow_Closed(object sender,EventArgs args) {
            double width = ActualWidth;
            double height = ActualHeight;
            Size size = new Size();
            size.Width = width;
            size.Height = height;
            CurrentConfigManagement currentConfig = CurrentConfigManagement.GetIntance();
            currentConfig.SaveMainWindowSize(size);
        }


        /* 追加内容至日志Box 
        参数为追加的内容及颜色
        执行本方法自动换行
        */
        private void AppendLog(string text, Brush brush)
        {
            try
            {
                Task appendLogTask = new Task(() =>
                {
                    App.Current.Dispatcher.Invoke(new Action(() =>
                    {
                        Run run = new Run();
                        run.Text = $"\n{DateTime.Now.ToString()} {text}";
                        run.Foreground = brush;
                        LogParagragh.Inlines.Add(run);
                    }));
                });
                appendLogTask.Start();
            }
            catch (Exception) { }
        }

        //恢复默认尺寸按钮点击时，恢复默认尺寸
        private void ResetSize_Click(object sender,RoutedEventArgs arg) {
            Height = 605.0;
            Width = 990.0;
            
        }

        //机型清单发生变化时,刷新可选机型列表
        private void ProductListChanged(object sender, ProductListChangedArgs args)
        {
            string productname = args.Productname;
            string changeType = args.ChangeType;
            List<string> productnameList = new List<string>();
            App.Current.Dispatcher.Invoke(new Action(() => {
                ItemCollection productNameCollion = ProductNameBox.Items;
                int count = productNameCollion.Count;
                string[] productArr = new string[count];
                productNameCollion.CopyTo(productArr, 0);
                productnameList = productArr.ToList();
                if (changeType.Equals("Add"))
                {
                    productnameList.Add(productname);
                }
                else
                {
                    productnameList.Remove(productname);
                }
                ProductNameBox.ItemsSource = null;
                ProductNameBox.ItemsSource = productnameList;
                string selectName = CurrentConfigManagement.GetIntance().GetSelectProductName();
                if (selectName == "")
                {
                    ProductNameBox.SelectedIndex = 0;
                }
                else
                {
                    ProductNameBox.SelectedValue = selectName;
                }
            }));
        }
    }
}
